package com.aaa.config;

import com.aaa.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * -*- coding:utf-8 -*-
 *
 * @author 太阳偷渡青山
 * @software IntelliJ IDEA
 * @date 2023/01/03 10:24
 * @Description
 */
@Configuration
public class MySecuityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    /**
     * 创建密码编码器
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 指定账户和密码的来源
     *
     * @param auth 身份验证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 放行登录表单资源
        http.formLogin()
                // 设置登录成功后的路径。该路径是接口路径，那么提交方式必须为post
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                // 登录成功后转发的路径
                .successForwardUrl("/main")
                // 登录失败后转发的路径
//                .failureForwardUrl("/fail")
                .permitAll();

        // 没有权限跳转路径
        http.exceptionHandling().accessDeniedPage("/403.html");

        //禁用跨站伪造请求,不使用csrf过滤器。
        http.csrf().disable();

        // 设置其他路径需要登录认证后才进行访问
        http.authorizeRequests().anyRequest().authenticated();
    }
}
